<?php
namespace haibao\cms\data;


class ForumThread extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ForumThread');
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
	}
	
	public function addArticleThread($threadInfo,$postInfo,$attach,$attachX){
		self::beginTranscation ();
		$threadArr = array();
		$pid = 0;
		try {
			$str = implode(',',array_pad($threadArr, count($threadInfo), '%s'));
			$threadSql = "INSERT INTO hb_forum_thread(fid,posttableid,typeid,sortid,readperm,price,author,authorid,subject,dateline,lastpost,lastposter,views,replies,displayorder,highlight,digest,rate,special,attachment,moderated,closed,stickreply,recommends,recommend_add,recommend_sub,heats,`status`,isgroup,favtimes,sharetimes,stamp,icon,pushedaid,cover,replycredit,relatebytag,maxposition,bgcolor,comments) VALUES (".$str.")";
			$this->query($threadSql,array_values($threadInfo));
			$tid = $this->getDb()->insert_id;
			
			$postTableSql = "insert into hb_forum_post_tableid()values()";
			$this->query($postTableSql);
			$pid = $this->getDb()->insert_id;
			
			$postInfo['tid'] = $tid;
			array_unshift($postInfo, $pid);
			$str = implode(',',array_pad(array(), count($postInfo), '%s'));
			$postSql = "INSERT INTO hb_forum_post(pid,fid,tid,first,author,authorid,subject,dateline,message,useip,invisible,anonymous,usesig,htmlon,bbcodeoff,smileyoff,parseurloff,attachment,rate,ratetimes,status,tags,comment,replycredit,from_wx,reply_pos) VALUES (".$str.")";
			$this->query($postSql,$postInfo);
	
			$upThreadSql = "UPDATE hb_forum_thread SET lastpost = %s,lastposter = %s,replies = replies + 1 WHERE tid = %s";
			$this->query($upThreadSql,array(time(),$threadInfo['author'],$tid));
			$tab_no = substr($tid, -1);
			if($attachX){
				foreach($attachX as $key=>$attachment){
					$aid = 0;
					if($attach){
						$attach['tid'] = $tid;
						$attach['pid'] = $pid;
						$attach['tableid'] = $tab_no;
						$str = implode(',',array_pad(array(), count($attach), '%s'));
						$attachSql =  "INSERT INTO hb_forum_attachment(tid,pid,uid,tableid,downloads) VALUES(".$str.")";
						$this->query($attachSql,$attach);
						$aid = $this->getDb()->insert_id;
						$attachment['aid'] = $aid;
						$attachment['tid'] = $tid;
						$attachment['pid'] = $pid;
						$attachmentStr = implode(',',array_pad(array(), count($attachment), '%s'));
						$attachmentSql = "INSERT INTO hb_forum_attachment_".$tab_no."(aid,tid,pid,uid,dateline,filename,filesize,attachment,remote,description,readperm,price,isimage,width,thumb,picid) VALUES(".$attachmentStr.")";
						$this->query($attachmentSql,$attachment);
					}
				}
				$upattachNumSql = "UPDATE hb_forum_post SET attachment= %s WHERE pid= %s";
				$this->query($upattachNumSql,array(count($attachX),$pid));
			}
			
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		
	}
	
}